// 加载环境变量
require("dotenv").config();

const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const createError = require("http-errors");

// 导入配置和中间件
const sessionMiddleware = require("./config/session");
const { initDatabase } = require("./models");
const loggerMiddleware = require("./middlewares/logger");
const { notFound, globalError } = require("./middlewares/errorHandler");

// 导入路由加载器
const { registerRoutes } = require("./config/routes");

// 初始化Express应用
const app = express();

// 设置视图引擎
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");

// 中间件
loggerMiddleware(app); // 日志
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use(sessionMiddleware); // 会话

// 初始化数据库
initDatabase();

// 注册路由
registerRoutes(app);

// 添加路由信息端点（用于调试和文档）
if (process.env.NODE_ENV === "development") {
  const { getRoutesInfo } = require("./config/routes");

  app.get("/debug/routes", (req, res) => {
    res.json({
      code: 200,
      message: "所有路由列表",
      data: getRoutesInfo(),
    });
  });

  console.log("🔍 路由调试端点已启用: GET /debug/routes");
}

// 错误处理
app.use(notFound);
app.use(globalError);

// 只有在直接运行此文件时才启动服务器
// 避免在通过 bin/www 启动时重复监听
if (require.main === module) {
  const PORT = process.env.PORT || 3000;
  app.listen(PORT, () => {
    console.log(`🚀 服务器运行在端口 ${PORT}`);
    console.log(`🌍 环境: ${process.env.NODE_ENV || "development"}`);
    console.log(`📎 访问地址: http://localhost:${PORT}`);
    console.log(`📊 API 基础路径: http://localhost:${PORT}/api`);
  });
}

module.exports = app;
